import React from 'react';
import { Button, Drawer, Empty, Layout, Tree } from 'antd';
import { Form } from '@ant-design/compatible';
import { connect } from 'dva';
import {PageHeaderLayout, StandardTable, PageCard, IconButton} from '../../components';
import { modalWidth, pageSize } from '../../../config';

const reqApi = 'sum';
const { Sider, Content } = Layout;

class page extends React.Component {
  state = {
    currentNavi: [],
    currentTitle: '全部',
    loadingNavi: false,
    loadingContent: false,
    visibleTree: false, // 树显隐
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    exporting: false,
  };

  componentDidMount() {
    this.funcGetTreeData();
  }

  // 获取树数据
  funcGetTreeData = () => {
    const { props } = this;
    props.dispatch({
      type: reqApi + '/tree',
      payload: {},
    }).then(this.funcGetListData);
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({ loadingContent: true });

    const { state } = this;
    const { pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const payload = {
      currentPage: current,
      pageSize,
    };

    if (state.currentNavi.length) {
      const [deptId, sum] = state.currentNavi[0].split('_');
      payload.deptId = parseInt(deptId);
      payload.sum = parseInt(sum);
    }

    dispatch({
      type: reqApi + '/list',
      payload,
    }).then(() => this.setState({ loadingContent: false }));
  };

  // 左侧树
  leftTree = () => {
    const { props } = this;
    const { treeData } = props[reqApi];

    if (treeData.length) {
      return (
        <div
          style={{
            maxHeight: 'calc(100vh - ' + (window.isMobile ? 56 : 120) + 'px)',
            overflow: 'auto',
          }}
        >
          <Tree
            blockNode
            defaultExpandAll
            treeData={treeData}
            onSelect={(selectedKeys, { selectedNodes }) => {
              const { deptName, title } = selectedNodes.length ? selectedNodes[0] : {};
              this.setState({
                currentNavi: selectedKeys,
                currentTitle: selectedNodes.length ? deptName + ' ' + title : '全部',
                visibleTree: false,
              }, this.funcGetListData);
            }}
          />
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 表格列
  columns = () => [
    {
      title: '学生姓名',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 50,
      render: text => text === '1' ? '男' : '女',
    },
    {
      title: '入学成绩',
      dataIndex: 'sum',
      width: 80,
      render: num => num > 0 ? num + '分' : '',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: "身份证号",
      dataIndex: "idCardNum",
      width: 180,
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '报考专业',
      dataIndex: 'specialName',
    },
  ];

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, counts } = props[reqApi];
    const { total, lodging1sex1, lodging1sex0, lodging0sex1, lodging0sex0 } = counts;
    const footerData = [];
    if (total) footerData.push('学生总数：' + total + '人');
    if (lodging1sex1) footerData.push('住校男生：' + lodging1sex1 + '人');
    if (lodging1sex0) footerData.push('住校女生：' + lodging1sex0 + '人');
    if (lodging0sex1) footerData.push('跑堂男生：' + lodging0sex1 + '人');
    if (lodging0sex0) footerData.push('跑堂女生：' + lodging0sex0 + '人');
    const footer = footerData.toString().replace(/,/g, '，');

    return (
      <div>
        <Button.Group>
          {window.isMobile ? (
            <Button
              type='primary'
              style={{ marginBottom: 16 }}
              onClick={() => this.setState({ visibleTree: true })}
            >选择分数</Button>
          ) : null}
          <IconButton
            text='导出'
            type={window.isMobile ? 'default' : 'primary'}
            loading={state.exporting}
            disabled={state.exporting || !total}
            onClick={this.funcExport}
            style={{marginBottom: 16}}
          />
        </Button.Group>

        <StandardTable
          loading={state.loadingContent}
          columns={this.columns()}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
          scrollX={1280}
          fixedNum
          footer={footer}
        />
      </div>
    );
  };

  // 导出
  funcExport = () => {
    this.setState({ exporting: true });

    const { state } = this;
    const { dispatch } = this.props;
    const payload = {
      currentPage: 1,
      pageSize: 10000,
    };

    if (state.currentNavi.length) {
      const [deptId, sum] = state.currentNavi[0].split('_');
      payload.deptId = parseInt(deptId);
      payload.sum = parseInt(sum);
    }

    dispatch({
      type: reqApi + '/listExport',
      payload,
    }).then(() => {
      this.setState({ exporting: false });

      const { props } = this;
      const { exportData, counts } = props[reqApi];
      localStorage.setItem('studentData', JSON.stringify(exportData));
      localStorage.setItem('studentCounts', JSON.stringify(counts));
      localStorage.setItem('studentTitle', state.currentTitle);

      const w = window.innerWidth, h = window.innerHeight;
      const win = window.open(
        'exportSum.html',
        '_blank',
        'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
      );
      if (win) {
        if (win.focus) {
          win.focus();
        }
      }
    });
  };

  render() {
    const { state, props } = this;

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          bodyStyle={{
            padding: 0,
            overflow: 'hidden',
          }}
          children={(
            <Layout>
              {window.isMobile ? null : (
                <Sider
                  theme='light'
                  width={220}
                  style={{ borderRight: '1px solid gainsboro' }}
                >
                  {this.leftTree()}
                </Sider>
              )}
              <Content
                style={{
                  padding: '16px 8px 0 8px',
                  backgroundColor: 'white',
                }}
              >
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title='选择分数'
          visible={state.visibleTree}
          onClose={() => this.setState({ visibleTree: false })}
          bodyStyle={{ padding: 0 }}
        >
          {this.leftTree()}
        </Drawer>

      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ sum, menu }) => ({ sum, menu }))(page2);
